package com.twu.biblioteca;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.util.ArrayList;

public class MoviesListParser {

    private ArrayList<Movie> movieList;

    public MoviesListParser() {
        movieList = new ArrayList<Movie>();
    }

    public ArrayList<Movie> getMovieList() {
        return movieList;
    }

    public ArrayList<Movie> parseXml(Document xmlDocument) {
        movieList = new ArrayList<Movie>();
        if(xmlDocument != null) {
            NodeList moviesNodeList = getMoviesNodeList(xmlDocument);

            for(int movieListIndex =0; movieListIndex < moviesNodeList.getLength() ; movieListIndex++)
                movieList.add(createMovieObj((Element) moviesNodeList.item(movieListIndex)));
        }

        return movieList;
    }

    private Movie createMovieObj(Element movieNode) {
        return new Movie(getTextValueFromNode(movieNode, "NAME"),
                getIntValueFromNode(movieNode, "YEAR"),
                getTextValueFromNode(movieNode, "DIRECTOR"),
                getIntValueFromNode(movieNode, "RATING"));
    }

    private String getTextValueFromNode(Element nodeElement, String nodeLabel) {
        NodeList nodesList = nodeElement.getElementsByTagName(nodeLabel);

        if(nodesList.getLength() > 0)
            return nodesList.item(0).getTextContent();

        return "";
    }

    private int getIntValueFromNode(Element nodeElement, String nodeLabel) {
        NodeList nodesList = nodeElement.getElementsByTagName(nodeLabel);

        if(nodesList.getLength() > 0)
            return Integer.parseInt(nodesList.item(0).getTextContent());

        return -1;
    }

    private NodeList getMoviesNodeList(Document xmlFile) {

        try
        {
            String xmlMovieLabel = "MOVIE";
            return xmlFile.getElementsByTagName(xmlMovieLabel);

        } catch (Exception e) {
            return (NodeList) new ArrayList();
        }
    }

}
